<template>
  <el-dialog
    :visible="visible"
    :title="title"
    class="add-dept-dialog"
    align-center
    @opened="handleDialogOpen"
    @close="closeDialog"
    width="562px"
  >
    <el-form
      :model="deptForm"
      :rules="deptRules"
      ref="deptFormRef"
      label-width="120px"
    >
      <el-form-item label="上级部门" prop="parentCode">
        <el-cascader
          :options="deptRoleDict"
          v-model="pkids"
          :props="cascaderProps"
          clearable
          placeholder="请选择"
          @change="handleParentCodeChange"
          :show-all-levels="false"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="areaName">
        <el-input v-model="deptForm.areaName" />
      </el-form-item>
      <el-form-item label="行政区划编码" prop="areaCode">
        <el-input v-model="deptForm.areaCode" />
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="deptForm.longitude" />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="deptForm.latitude" />
      </el-form-item>
      <el-form-item label="是否参与体检" prop="status">
        <el-switch
          v-model="deptForm.status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { Message as ElMessage } from 'element-ui'
import { addDept, updateDept, updateDeptNew } from '@/api/back-management/dept'
import type { DivisionData, ValidatorCallback } from '@/utils/type'

const cascaderProps = {
  checkStrictly: true,
  label: 'areaName',
  value: 'pkid',
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  deptInfo: {
    type: Object,
    default: () => {},
  },
  deptRoleDict: {
    type: Array,
    default: () => [],
  },
  allDeptDict: {
    type: Array,
    default: () => [],
  },
})

const title = ref('新增部门')

const pkids = ref<string[]>([])

const emit = defineEmits(['closeDialog', 'updateDept'])

const closeDialog = () => {
  emit('closeDialog')
}

const deptForm = reactive({
  areaName: '',
  parentCode: '',
  areaCode: '',
  longitude: '',
  latitude: '',
  pkid: '',
  status: 0,
})

const deptFormRef = ref()

const lngValidator = (
  rule: any,
  value: number,
  callback: ValidatorCallback
) => {
  if (value > 180 || value < -180) {
    callback(new Error('请输入正确的经度'))
  } else {
    callback()
  }
}

const latValidator = (
  rule: any,
  value: number,
  callback: ValidatorCallback
) => {
  if (value > 90 || value < -90) {
    callback(new Error('请输入正确的纬度'))
  } else {
    callback()
  }
}

const deptRules = reactive({
  areaName: [
    {
      required: true,
      message: '部门名称不能为空',
      trigger: 'blur',
    },
  ],
  parentCode: [
    {
      required: true,
      message: '请选择上级部门',
      trigger: 'change',
    },
  ],
  areaCode: [
    {
      required: true,
      message: '区域编码不能为空',
      trigger: 'blur',
    },
  ],
  longitude: [
    {
      required: false,
      message: '经度不能为空',
      trigger: 'blur',
    },
    {
      validator: lngValidator,
      trigger: 'blur',
    },
  ],
  latitude: [
    {
      required: false,
      message: '纬度不能为空',
      trigger: 'blur',
    },
    {
      validator: latValidator,
      trigger: 'blur',
    },
  ],
})

const onSubmit = () => {
  deptFormRef.value?.validate((valid) => {
    if (valid) {
      const params = {
        areaName: deptForm.areaName,
        parentCode: deptForm.parentCode,
        areaCode: deptForm.areaCode,
        longitude: deptForm.longitude,
        latitude: deptForm.latitude,
        status: deptForm.status,
        pkid: deptForm.pkid,
      }
      if (deptForm.pkid) {
        updateDeptNew(params)
          .then((res) => {
            if (res.success) {
              emit('updateDept')
              ElMessage.success('更新区域成功！')
            } else {
              ElMessage.error(res.message)
            }
          })
          .catch((e) => {
            ElMessage.error(e)
          })
      } else {
        params.pkid = ''
        addDept(params)
          .then((res) => {
            if (res.success) {
              emit('updateDept')
              ElMessage.success('添加区域成功！')
            } else {
              ElMessage.error(res.message)
            }
          })
          .catch((e) => {
            ElMessage.error(e)
          })
      }
    }
  })
}

const handleParentCodeChange = (item) => {
  const val = item as string[]
  if (val) {
    deptForm.parentCode = val[val.length - 1]
  } else {
    deptForm.parentCode = ''
  }
}

const extractIds = (
  treeArray: DivisionData[],
  nodeId: string
): string[] | null => {
  // Find the node with the given ID
  const findNode = (
    node: DivisionData,
    pkid: string,
    parents: string[] = []
  ): string[] | null => {
    if (node.pkid === pkid) {
      return parents.concat(node.pkid)
    }

    if (Array.isArray(node.children)) {
      for (const child of node.children) {
        const found = findNode(child, pkid, parents.concat(node.pkid))
        if (found) {
          return found
        }
      }
    }

    return null
  }

  // Start the search from the root of the tree
  for (const node of treeArray) {
    const result = findNode(node, nodeId)
    if (result) {
      return result
    }
  }

  // If the node is not found, return null or handle the error as desired
  return null
}

const handleDialogOpen = () => {
  deptFormRef.value?.resetFields()
  if (props.deptInfo) {
    const {
      pkid,
      areaCode,
      areaName,
      parentCode,
      longitude,
      latitude,
      status,
    } = props.deptInfo
    deptForm.pkid = pkid || ''
    deptForm.areaName = areaName || ''
    deptForm.areaCode = areaCode || ''
    deptForm.parentCode = parentCode || ''
    deptForm.longitude = longitude || ''
    deptForm.latitude = latitude || ''
    deptForm.status = status || 0
    // if (level) {
    //   const lenArr = [6,9,12]
    //   const arr = lenArr.slice(0,+level)
    //   const res = arr.map((val) => {
    //     return areaCode.slice(0,val)
    //   })
    // }
    pkids.value = []
    if (pkid) {
      title.value = '编辑部门'
      const res = extractIds(props.allDeptDict!, pkid)
      if (res) {
        res.pop()
        pkids.value = res
      }
      // console.log(pkids.value)
    } else {
      title.value = '新增部门'
    }
  }
}
</script>

<style lang="scss">
.add-dept-dialog {
  //width: 562px;
  //height: 503px;
  //background: #ffffff;
  border-radius: 4px;

  .el-dialog__body {
    padding-bottom: 0 !important;
  }
  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-form {
    .el-form-item {
      min-height: 42px;
      margin-bottom: 21px;
      align-items: center;
    }

    .el-cascader {
      width: 100%;
    }

    .el-select {
      width: 100%;
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
